How to use Python Lambda functions: a 5 minute tutorial | 您所在的位置:网站首页 › key=lambda x:x[1] › How to use Python Lambda functions: a 5 minute tutorial |
How to implement Python lambda functions
A lambda function is declared differently than a normal function. In Python, lambda functions have the following unique characteristics: It can only contain expressions It cannot include statements in its body It is written as a single line It does not support type annotations It can be immediately invokedA lambda function in Python uses the following basic syntax. As we mentioned before, we use the lambda keyword to create a simple function in a Python expression. lambda arguments: expressionA lambda expression can have any number of arguments (including none). For example: lambda: 1 # No arguments lambda x, y: x + y lambda a, b, c, d: a*b + c*dIn the following example, we use a lambda function to replace an area function: lambda x: x[0]*x[1]The lambda keyword identifies the lambda expression. In the above example, x is the only parameter. The colon ends the parameter list and introduces the body of the function. To use this expression properly, you place it wherever you might normally use a function object. This piece of code below creates a temporary, anonymous function object and passes it into the sorted function, which then performs the sort. |
CopyRight 2018-2019 实验室设备网 版权所有 |